import { StatisticCard } from '@ant-design/pro-components';
import { Tooltip } from 'antd';
import React, { ReactNode, useMemo } from 'react';
import styles from './CustomStatisticCard.module.less';

export interface CustomStatisticCardProps {
  title: string;
  value: string | number;
  icon?: ReactNode;
  prefix?: ReactNode;
  suffix?: ReactNode;
  status?: 'success' | 'processing' | 'default' | 'error' | 'warning';
  maxWidth?: number; // 文本最大宽度，超出则显示省略号
  placement?: 'top' | 'bottom' | 'left' | 'right'; // Tooltip显示位置
  bordered?: boolean;
  hoverable?: boolean;
  onClick?: () => void;
  loading?: boolean;
  className?: string;
  style?: React.CSSProperties;
}

const CustomStatisticCard: React.FC<CustomStatisticCardProps> = ({
  title,
  value,
  icon,
  prefix,
  suffix,
  status,
  maxWidth = 150,
  placement = 'top',
  bordered = false,
  hoverable = false,
  onClick,
  loading = false,
  className,
  style,
}) => {
  // 判断是否需要显示省略号
  const { displayValue, needTooltip } = useMemo(() => {
    const valueStr = String(value);
    // 简单估算文本长度，中文字符算2个字符宽度
    const estimatedWidth =
      valueStr.replace(/[\u4e00-\u9fa5]/g, 'aa').length * 8;
    const needEllipsis = estimatedWidth > maxWidth;

    return {
      displayValue: valueStr,
      needTooltip: needEllipsis,
    };
  }, [value, maxWidth]);

  // 自定义渲染带省略号的值
  const renderValue = () => {
    if (!needTooltip) return displayValue;

    return (
      <Tooltip title={displayValue} placement={placement}>
        <div
          className={styles.ellipsisText}
          style={{ maxWidth: `${maxWidth}px` }}
        >
          {displayValue}
        </div>
      </Tooltip>
    );
  };

  // 直接返回StatisticCard，保持原有的组件结构
  return (
    <StatisticCard
      statistic={{
        title,
        value: needTooltip ? undefined : displayValue,
        valueRender: needTooltip ? renderValue : undefined,
        icon,
        prefix,
        suffix,
        status,
      }}
      bordered={bordered}
      hoverable={hoverable}
      onClick={onClick}
      loading={loading}
      className={`${styles.cardContent} ${className || ''}`}
      style={style}
    />
  );
};

export default CustomStatisticCard;
